<?php
namespace Home\Controller;
use Think\Controller;
class SingleController extends Controller {
	public function index(){

		if(isset($_SESSION['username'])){
        	$this->assign('login','true');
        	$this->assign('username',$_SESSION['username']);
        }

        //当前登录用户的id
        $userId=$_SESSION['id'];
        $phone = D('phone');
        //获取跳转URL中的商品的id
        $Id = $_GET[id]; // 分类

        //获取指定id的手机
        $singlephone=$phone->where("id = '$Id'")->select();
        $this->assign('singlephone',$singlephone);

  

		$this->display();
	}

     //添加购物车
    public function addCart(){
        $userId = $_SESSION['id'];
        $phoneid = $_POST['phoneid'];
        $phonename = $_POST['phonename'];
        $type = $_POST['type'];
        $discountprice = $_POST['discountprice'];
        $price = $_POST['price'];
        
        $cart = D('cart');
        $number =$cart->where(" phoneid = '$phoneid'")->getField('number');
        $id = $cart->where("phoneid ='$phoneid' AND userid='$userId'")->getField('id');
        if($id > 0){
            $number = $number + 1;
            $cart->where(" phoneid = '$phoneid'")->setField('number',$number);
            $result = array(
                'code' => '0',
                'ext' => '添加成功'
            );
            echo json_encode($result/*,JSON_UNESCAPED_UNICODE*/);

        }else{
            $data['userid'] = $userId;
            $data['phoneid'] = $phoneid;
            $data['phonename'] = $phonename;
            $data['type'] = $type;
            $data['discountprice'] = $discountprice;
            $data['price'] = $price;
            $data['number'] = 1;
            if($cart->create($data)){
                $id= $cart->add();
                if($id){
                    $cart_template = $cart->where("id='$id'")->find();
                    $result = array(
                        'code' => '0',
                        'ext' => 'success',
                        'obj' => $cart_template
                    );
                    echo json_encode($result);
                }
            }
        }
    }

     //退出
    public function doLogout(){
        $_SESSION = array();
        if(isset($_COOKIE[session_name()])){
            setcookie(session_name(),'',time()-1,'/');
        }
        session_destroy();
        $this->redirect('Index/index');
    }

   
}